<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="floating-shape shape-1"></div>
      <div class="floating-shape shape-2"></div>
      <div class="floating-shape shape-3"></div>
      <div class="floating-shape shape-4"></div>
    </div>
    
    <div class="login-content">
      <!-- 左侧装饰区域 -->
      <div class="login-left">
        <div class="brand-section">
          <div class="logo-container">
            <div class="logo-icon">🐾</div>
          </div>
          <h1 class="brand-title">宠物管理系统</h1>
          <p class="brand-subtitle">Pet Management System</p>
          <div class="brand-description">
            <p>专业的宠物医疗管理平台</p>
            <p>为您的宠物提供最好的服务</p>
          </div>
        </div>
      </div>
      
      <!-- 右侧登录表单 -->
      <div class="login-right">
        <div class="login-form-container">
          <!-- 登录表单 - 增加v-if条件控制显示 -->
          <div v-if="!showRegisterForm">
            <div class="form-header">
              <h2>欢迎回来</h2>
              <p>请登录您的账户</p>
            </div>
            
            <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form" @keyup.enter="handleLogin">
              <el-form-item prop="username">
                <el-input v-model="loginForm.username" placeholder="请输入用户名" size="large" class="custom-input">
                  <template #prefix>
                    <el-icon class="input-icon"><User /></el-icon>
                  </template> 
                </el-input> 
              </el-form-item>

              <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" size="large" class="custom-input" show-password>
                  <template #prefix>
                    <el-icon class="input-icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" size="large" :loading="authStore.loading" class="login-button" @click="handleLogin" >
                  <el-icon v-if="!authStore.loading"><Right /></el-icon>
                  {{ authStore.loading ? '登录中...' : '登录' }}
                </el-button>
              </el-form-item>
            </el-form> 
            
            <!-- 新增：注册按钮 -->
            <div class="login-actions">
              <el-button type="text" @click="showRegisterForm = true">立即注册</el-button>
            </div>
          </div>
          
          <!-- 注册表单 -->
          <div v-if="showRegisterForm">
            <div class="form-header">
              <h2>创建新账户</h2>
              <p>请填写注册信息</p>
            </div>
            
            <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" class="login-form">
              <el-form-item prop="username">
                <el-input v-model="registerForm.username" placeholder="请设置账户名称" size="large" class="custom-input">
                  <template #prefix>
                    <el-icon class="input-icon"><User /></el-icon>
                  </template> 
                </el-input>
              </el-form-item>

              <el-form-item prop="password">
                <el-input v-model="registerForm.password" type="password" placeholder="请设置密码" size="large" class="custom-input" show-password>
                  <template #prefix>
                    <el-icon class="input-icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="confirmPassword">
                <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" size="large" class="custom-input" show-password>
                  <template #prefix>
                    <el-icon class="input-icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-button 
                  type="primary" 
                  size="large" 
                  :loading="registerLoading" 
                  class="login-button" 
                  @click="handleRegister"
                >
                  <el-icon v-if="!registerLoading"><Right /></el-icon>
                  {{ registerLoading ? '注册中...' : '注册' }}
                </el-button>
              </el-form-item>
            </el-form>
            
            <!-- 注册表单的返回登录按钮 -->
            <div class="login-actions">
              <el-button type="text" @click="showRegisterForm = false">返回登录</el-button>
            </div>
          </div>
          
          <div class="login-footer">
            <div class="test-accounts">
              <h4>请输入用户名和密码以登录</h4>
              <div class="account-item">
                <span class="account-label">账号示例：</span>
                <span class="account-info">admin / admin123</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Right } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { usePermissionStore } from '@/stores/permission'
import axios from 'axios'
import qs from 'qs'
import { md5 } from 'js-md5' // 密码加密

const router = useRouter()
const authStore = useAuthStore()
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()

// 登录表单
const loginForm = reactive({
  username: '',
  password: '' // 明文，提交前加密
})
    
// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})

// 表单显示控制
const showRegisterForm = ref(false)
const registerLoading = ref(false)

// 表单验证规则（与后端一致：5-16位非空）
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '账户名称长度为5-16个字符', trigger: 'blur' },
    { pattern: /^\S+$/, message: '用户名不能包含空格', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度为5-16个字符', trigger: 'blur' },
    { pattern: /^\S+$/, message: '密码不能包含空格', trigger: 'blur' }
  ]
}

const registerRules: FormRules = {
  username: [
    { required: true, message: '请设置账户名称', trigger: 'blur' },
    { min: 5, max: 16, message: '账户名称长度为5-16个字符', trigger: 'blur' },
    { pattern: /^\S+$/, message: '用户名不能包含空格', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度为5-16个字符', trigger: 'blur' },
    { pattern: /^\S+$/, message: '密码不能包含空格', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ]
}

// 处理登录（密码加密后提交）
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    console.log('表单验证通过，开始登录')
    
    // 密码MD5加密（与后端一致）
    const encryptedPwd = md5(loginForm.password)
    
    // 调用store登录（假设authStore.login会发送加密后的密码）
    const success = await authStore.login({
      username: loginForm.username,
      password: encryptedPwd
    })
    
    console.log('登录结果:', success)
    
   // 修改 handleLogin 函数中的成功处理逻辑
if (success) {
  const permissionStore = usePermissionStore()
  const routes = await permissionStore.generateRoutes()
  
  // 先添加所有动态路由
  routes.forEach(route => router.addRoute(route))
  
  // 强制刷新当前路由（关键步骤）
  const redirectPath = '/home'
  router.replace(redirectPath).then(() => {
    // 确保路由更新后跳转
    window.location.reload()
  })
} else {
      console.log('登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
  }
}

// 处理注册（保持原逻辑，密码明文提交，后端加密）
const handleRegister = async () => {
  if (!registerFormRef.value) return  
  try {
    await registerFormRef.value.validate()
    registerLoading.value = true
    
    const registerData = {
      username: registerForm.username,
      password: registerForm.password // 明文，后端会加密
    }
    
    const response = await axios.post(
      'http://localhost:8080/user/register', 
      qs.stringify(registerData), 
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
    )
    
    if (response.data.code === 200) {
      ElMessage.success('注册成功！请登录')
      showRegisterForm.value = false
      loginForm.username = registerForm.username
      registerForm.username = ''
      registerForm.password = ''
      registerForm.confirmPassword = ''
    } else {
      throw new Error(response.data.message || '注册失败')
    }
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error(error.message || '注册失败，请检查表单')
  } finally {
    registerLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.shape-1 {
  width: 80px;
  height: 80px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 120px;
  height: 120px;
  top: 20%;
  right: 15%;
  animation-delay: 2s;
}

.shape-3 {
  width: 60px;
  height: 60px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 10%;
  right: 10%;
  animation-delay: 1s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 主要内容区域 */
.login-content {
  display: flex;
  width: 100%;
  max-width: 1000px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  overflow: hidden;
  z-index: 2;
  position: relative;
}

/* 左侧装饰区域 */
.login-left {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 40px;
  position: relative;
  overflow: hidden;
}

.login-left::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" fill="white" opacity="0.05"/></svg>');
  background-size: 100px;
  z-index: 1;
}

.brand-section {
  text-align: center;
  color: white;
  z-index: 2;
  position: relative;
}

.logo-container {
  margin-bottom: 30px;
}

.logo-icon {
  font-size: 80px;
  animation: bounce 2s ease-in-out infinite;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

.brand-title {
  font-size: 36px;
  font-weight: 700;
  margin: 0 0 10px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.brand-subtitle {
  font-size: 18px;
  margin: 0 0 30px 0;
  opacity: 0.9;
  font-weight: 300;
}

.brand-description {
  font-size: 16px;
  line-height: 1.6;
  opacity: 0.8;
}

.brand-description p {
  margin: 8px 0;
}

/* 右侧登录表单 */
.login-right {
  flex: 1;
  padding: 60px 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-form-container {
  width: 100%;
  max-width: 400px;
}

.form-header {
  text-align: center;
  margin-bottom: 40px;
}

.form-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
}

.form-header p {
  font-size: 16px;
  color: #909399;
  margin: 0;
}

.login-form {
  margin-bottom: 30px;
}

.custom-input {
  --el-input-height: 50px;
  --el-input-border-radius: 12px;
  --el-input-bg-color: #f8f9fa;
  --el-input-border-color: #e9ecef;
  --el-input-hover-border-color: #667eea;
  --el-input-focus-border-color: #667eea;
}

.custom-input :deep(.el-input__wrapper) {
  box-shadow: none;
  border: 2px solid var(--el-input-border-color);
  transition: all 0.3s ease;
}

.custom-input :deep(.el-input__wrapper:hover) {
  border-color: var(--el-input-hover-border-color);
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--el-input-focus-border-color);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.input-icon {
  font-size: 18px;
  color: #909399;
}

.login-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
}

.login-button:active {
  transform: translateY(0);
}

.login-footer {
  text-align: center;
  padding-top: 30px;
  border-top: 1px solid #f0f0f0;
}

.login-tips h4 {
  font-size: 14px;
  color: #606266;
  margin: 0 0 15px 0;
  font-weight: 500;
}

.login-tips p {
  font-size: 12px;
  color: #909399;
  margin: 0;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .login-content {
    max-width: 900px;
    margin: 0 20px;
  }
  
  .login-left {
    padding: 50px 30px;
  }
  
  .login-right {
    padding: 50px 40px;
  }
  
  .brand-title {
    font-size: 32px;
  }
  
  .logo-icon {
    font-size: 70px;
  }
}

@media (max-width: 768px) {
  .login-container {
    padding: 15px;
  }
  
  .login-content {
    flex-direction: column;
    max-width: 450px;
    margin: 0 auto;
  }
  
  .login-left {
    padding: 40px 20px;
    min-height: 200px;
  }
  
  .login-right {
    padding: 40px 30px;
  }
  
  .brand-title {
    font-size: 28px;
  }
  
  .brand-subtitle {
    font-size: 16px;
  }
  
  .logo-icon {
    font-size: 60px;
  }
  
  .form-header h2 {
    font-size: 24px;
  }
  
  .form-header p {
    font-size: 14px;
  }
  
  .custom-input {
    --el-input-height: 45px;
  }
  
  .login-button {
    height: 45px;
    font-size: 15px;
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 10px;
  }
  
  .login-content {
    border-radius: 15px;
    max-width: 100%;
    margin: 0;
  }
  
  .login-left {
    padding: 30px 15px;
    min-height: 180px;
  }
  
  .login-right {
    padding: 30px 20px;
  }
  
  .brand-title {
    font-size: 24px;
  }
  
  .brand-subtitle {
    font-size: 14px;
    margin: 0 0 20px 0;
  }
  
  .brand-description {
    font-size: 14px;
  }
  
  .logo-icon {
    font-size: 50px;
    margin-bottom: 20px;
  }
  
  .form-header {
    margin-bottom: 30px;
  }
  
  .form-header h2 {
    font-size: 22px;
  }
  
  .form-header p {
    font-size: 13px;
  }
  
  .custom-input {
    --el-input-height: 42px;
    --el-input-border-radius: 8px;
  }
  
  .login-button {
    height: 42px;
    font-size: 14px;
    border-radius: 8px;
  }
  
  .login-footer {
    padding-top: 20px;
  }
  
  .login-tips h4 {
    font-size: 13px;
  }
  
  .login-tips p {
    font-size: 11px;
  }
}

@media (max-width: 360px) {
  .login-container {
    padding: 5px;
  }
  
  .login-content {
    border-radius: 12px;
  }
  
  .login-left {
    padding: 25px 10px;
    min-height: 160px;
  }
  
  .login-right {
    padding: 25px 15px;
  }
  
  .brand-title {
    font-size: 22px;
  }
  
  .brand-subtitle {
    font-size: 13px;
  }
  
  .logo-icon {
    font-size: 45px;
  }
  
  .form-header h2 {
    font-size: 20px;
  }
  
  .form-header p {
    font-size: 12px;
  }
  
  .custom-input {
    --el-input-height: 40px;
  }
  
  .login-button {
    height: 40px;
    font-size: 13px;
  }
}

/* 横屏适配 */
@media (max-height: 600px) and (orientation: landscape) {
  .login-container {
    padding: 10px;
  }
  
  .login-content {
    max-width: 800px;
  }
  
  .login-left {
    padding: 30px 20px;
  }
  
  .login-right {
    padding: 30px 30px;
  }
  
  .brand-title {
    font-size: 24px;
  }
  
  .brand-subtitle {
    font-size: 14px;
    margin: 0 0 15px 0;
  }
  
  .logo-icon {
    font-size: 50px;
    margin-bottom: 15px;
  }
  
  .form-header {
    margin-bottom: 25px;
  }
  
  .form-header h2 {
    font-size: 20px;
  }
  
  .form-header p {
    font-size: 12px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 320px) {
  .login-container {
    padding: 5px;
  }
  
  .login-content {
    border-radius: 10px;
  }
  
  .login-left {
    padding: 20px 8px;
    min-height: 140px;
  }
  
  .login-right {
    padding: 20px 12px;
  }
  
  .brand-title {
    font-size: 20px;
  }
  
  .brand-subtitle {
    font-size: 12px;
  }
  
  .logo-icon {
    font-size: 40px;
  }
  
  .form-header h2 {
    font-size: 18px;
  }
  
  .form-header p {
    font-size: 11px;
  }
  
  .custom-input {
    --el-input-height: 38px;
  }
  
  .login-button {
    height: 38px;
    font-size: 12px;
  }
}
</style>